//
//  UITextFieldHelper.swift
//  CommonTools
//
//  Created by xianquan on 2024/1/11.
//

import Foundation

public extension UITextField {
    static var patternKey: String.Pattern = .none
    
    var pattern: String.Pattern {
        get {
            return getAssociatedValue(forKey: &UITextField.patternKey) as? String.Pattern ?? .none
        }
        set {
            setAssociateValue(newValue, withKey: &UITextField.patternKey)
        }
    }
    
    func limitInput(type: String.Pattern? = nil, limitCount: Int = -1){
        if let type = type {
            pattern = type
        }
        guard let _ = markedTextRange else {
            guard let selectedTextRange = selectedTextRange else {return}
            let cursorPosition = offset(from: endOfDocument, to: selectedTextRange.end)
            // 替换后的字符串
            var str = ""
            if pattern.rawValue.isEmpty {
                str = text ?? ""
            }
            else{
                str = text?.regularReplace(pattern, with: "") ?? ""
            }
            // 如果长度超出限制直接截断
            if limitCount >= 0, str.count > limitCount {
                str = String(str.prefix(limitCount))
            }
            text = str
            // 让光标停留在正确位置
            if let targetPosion = position(from: endOfDocument, offset: cursorPosition){
                self.selectedTextRange = textRange(from: targetPosion, to: targetPosion)
            }
            return
        }
    }
}
